package org.mytools.util;

import java.util.HashMap;
import java.util.Map;

import org.mytools.util.encrypt.MD5;

import net.sf.cglib.beans.BeanCopier;

public class BeanUtils {

	private static Map<String, BeanCopier> beanCopierCacheMap = new HashMap<String, BeanCopier>();

	private static <E, T> BeanCopier getBeanCopier(Class<E> fromObjectClazz,
			Class<T> toClazz) {
		String key = new MD5().encrypt(fromObjectClazz.getSimpleName()
				+ toClazz.getSimpleName());

		BeanCopier beanCopier = beanCopierCacheMap.get(key);
		if (null == beanCopier) {
			beanCopier = BeanCopier.create(fromObjectClazz, toClazz, false);
			beanCopierCacheMap.put(key, beanCopier);
		}

		return beanCopier;
	}

	public static <E, T> T copy(E fromObject, Class<T> toClazz) {
		T toObject;
		try {
			toObject = toClazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		BeanCopier beanCopier = getBeanCopier(fromObject.getClass(), toClazz);
		beanCopier.copy(fromObject, toObject, null);

		return toObject;
	}

	public static <E, T> T copy(E fromObject, T toObject) {
		BeanCopier beanCopier = getBeanCopier(fromObject.getClass(),
				toObject.getClass());
		beanCopier.copy(fromObject, toObject, null);

		return toObject;
	}

}
